package top.dyzmj.detty.core.utils.concurrent.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.dyzmj.detty.core.utils.SystemPropertyUtil;
import top.dyzmj.detty.core.utils.concurrent.ThreadProperties;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * 描述: {@link OrderedEventExecutor}的抽象基类，它在单个线程中执行所有提交的任务。
 *
 * @author dongYu
 * @date 2021/11/26
 */
public abstract class SingleThreadEventExecutor extends AbstractScheduledEventExecutor implements OrderedEventExecutor {

	static final int DEFAULT_MAX_PENDING_EXECUTOR_TASKS = Math.max(16,
			SystemPropertyUtil.getInt("top.detty.eventexecutor.maxPendingTasks", Integer.MAX_VALUE));

	private static final Logger logger = LoggerFactory.getLogger(SingleThreadEventExecutor.class);

	/**
	 * 线程未启动
	 */
	private static final int ST_NOT_STARTED = 1;
	/**
	 * 线程已启动
	 */
	private static final int ST_STARTED = 2;
	/**
	 * 线程正在关闭
	 */
	private static final int ST_SHUTTING_DOWN = 3;
	/**
	 * 线程已关闭
	 */
	private static final int ST_SHUTDOWN = 4;
	/**
	 * 线程已终止
	 */
	private static final int ST_TERMINATED = 5;

	private static final Runnable NOOP_TASK = () -> {
		//Nothing to do
	};

	private static final AtomicIntegerFieldUpdater<SingleThreadEventExecutor> STATE_UPDATER =
			AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "state");
	private static final AtomicReferenceFieldUpdater<SingleThreadEventExecutor, ThreadProperties> PROPERTIES_UPDATER =
			AtomicReferenceFieldUpdater.newUpdater(
					SingleThreadEventExecutor.class, ThreadProperties.class, "threadProperties");

//	private final Queue<Runnable> taskQueue;
	private final CountDownLatch threadLock = new CountDownLatch(1);
	private final Set<Runnable> shutdownHooks = new LinkedHashSet<Runnable>();
	private volatile Thread thread;
	@SuppressWarnings("unused")
	private volatile ThreadProperties threadProperties;
	//	private final Executor executor;
	private volatile boolean interrupted;
//	private final boolean addTaskWakesUp;
//	private final int maxPendingTasks;
//	private final RejectedExecutionHandler rejectedExecutionHandler;
	private long lastExecutionTime;

	@SuppressWarnings({"FieldMayBeFinal", "unused"})
	private volatile int state = ST_NOT_STARTED;

	private volatile long gracefulShutdownQuietPeriod;
	private volatile long gracefulShutdownTimeout;
	private long gracefulShutdownStartTime;

}
